﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CrmAttachmentImage
{
    public static class Parameters
    {
        public static Dictionary<String, String> Parameterize(string text)
        {
            var key = string.Empty;
            var arguments = new Dictionary<String, String>();
            var sb = new StringBuilder();
            var inquotes = false;
            for (var i = 0; i < text.Length; i++)
            {
                var t = text[i];
                if (t == '\'')
                {
                    // Handle double '' s and convert them to single '
                    if (i + 1 < text.Length && text[i + 1] == '\'')
                    {
                        i++;
                        sb.Append(t);
                        continue;
                    }
                    inquotes = !inquotes;
                }
                if (!inquotes && t == '=')
                {
                    key = sb.ToString().ToLower();
                    sb.Clear();
                    continue;
                }
                if (!inquotes && t == '|')
                {
                    arguments.Add(key, TrimQuotes(sb).ToString());
                    sb.Clear();
                    continue;
                }
                sb.Append(t);
            }
            // dump remainder
            arguments.Add(key, TrimQuotes(sb).ToString());
            return arguments;
        }

        private static StringBuilder TrimQuotes(StringBuilder value)
        {
            if (value[0] == '\'')
                value = value.Remove(0, 1);
            if (value[value.Length - 1] == '\'')
                value = value.Remove(value.Length - 1, 1);
            return value;
        }

        public static int GetIntegerParameter(Dictionary<string, string> par, string key, int defaultvalue = 0)
        {
            if (par.ContainsKey(key))
            {
                int maxwidth;
                if (Int32.TryParse(par[key], out maxwidth))
                {
                    return maxwidth;
                }
            }
            return defaultvalue;
        }
    }
}